<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;



use app\common\model\EthAccount;
use app\common\model\EthAccountLog;
use app\common\model\Idcard;
use app\common\model\InterestAllocation;
use app\common\model\Member;
use app\common\model\OtcFeedback;
use app\common\model\OtcInterestLog;
use app\common\model\OtcOrder;
use app\common\model\OtcShop;
use app\common\model\OtcTrading;
use app\common\model\ShopAccountLog;
use app\common\model\Transfer;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserPayType;
use app\common\model\UserRankingData;
use app\common\model\UserSms;
use app\common\model\Wallet;
use think\Db;

/**
 * 商铺逻辑
 */
class Shop extends ApiBase
{





    /***
     * 商铺详情
     */

    public function apply_shop_detail($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $info=$this->modelOtcShop->getInfo(['id'=>$data['id']],'full_face_photo_id,id,negative_photo_id,hand_held_photo_id,idcard,pay_type,shop_name,true_name,wallet_id');
        $arr['fromData']=$info;
        $arr['Other']=[];
        $arr['Other']['pay_arr']=explode(',',$info['pay_type']);
        $arr['Other']['full_face_photo']=$info->hand_held_photo;
        $arr['Other']['negative_photo']=$info->hand_held_photo;
        $arr['Other']['hand_held_photo']=$info->hand_held_photo;
        $arr['success_id']=$this->modelOtcShop->where(['user_id'=>$uid,'state'=>2])->column('wallet_id');
        $arr['apply_id']=$this->modelOtcShop->where(['user_id'=>$uid,'state'=>1])->column('wallet_id');
        $arr['fail_id']=$this->modelOtcShop->where(['user_id'=>$uid,'state'=>3])->column('wallet_id');
        unset($info->wallet);
        return $arr;
    }

    /***
     * 商铺详情
     */

    public function queuing_statistics($data){
        $price=getPrice();
        $btcs=[];
//        $ids=OtcShop::where()->column('id');
        foreach ($price as $k=>$v){
            $arr['name']=$v;
            $arr['count']=$this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where(['surplus_total'=>$v,'a.state'=>0,'a.shop_id'=>$data['shop_id'],'type'=>$data['type']])->count();
            $btcs[]=$arr;
        }

        return $btcs;
    }


    /***
     * 商铺详情
     */

    public function shop_detail($data){
//        $member=$this->logicApiBase->member;
//        $uid=$member['id'];

        $info=$this->modelOtcShop->getInfo(['id'=>$data['id']]);

        if($info['status']!=1){
            return  ajaxreturn(1,lang('您的店铺').$info->wallet->data['name'].lang('类型，应违反重大交易规则，已被封闭，如有疑问，请联系客服处理'));
        }
        $info['is_phone']=1;
        $info['is_real_name']=1;
        $info['full_face_photo']=$info->hand_held_photo;
        $info['negative_photo']=$info->hand_held_photo;
        $info['hand_held_photo']=$info->hand_held_photo;
        $info['is_advertisers']=1;
        $info['image']=$info->member->avtar;
        
        $info['parities']=$info->wallet->data['parities'];
        
        $uid=$info['user_id'];
        $info['order_count']=$this->modelOtcOrder->where(['otc_type'=>$data['type'],'shop_id'=>$info['id']])->count();
        $info['days_order_count']=$this->modelOtcOrder->where(['shop_id'=>$info['id'],'otc_type'=>$data['type'],'create_time'=>['between',[TIME_NOW-86400*30,TIME_NOW]]])->count();
        $info['wallet_name']=$info->wallet->data['name'];
        $info['success_order_count']=$this->modelOtcOrder->where(['shop_id'=>$info['id'],'otc_type'=>$data['type'],'state'=>['in',[2,9,10]]])->count();;
        $info['completion_rate']= $info['order_count']==0?0:$info['success_order_count']/$info['order_count']*100;
        $info['total_price']= $this->modelOtcTrading->where(['shop_id'=>$info['id'],'type'=>$data['type'],'state'=>0])->sum('total')+0;
        $info['max_total_price']=get_max_number($info['total_price']);
        $info['success_total_price']= $this->modelOtcOrder->where(['shop_id'=>$info['id'],'state'=>2,'otc_type'=>$data['type']])->sum('total')+0;
        $info['max_success_total_price']=get_max_number($info['success_total_price']);
        if($data['type']==1){
            $butie= OtcInterestLog::where(['user_id'=>$uid,'interest_type'=>2 ])->sum('substitute_money')+0;
        }else{
            $butie= OtcInterestLog::where(['user_id'=>$uid,'interest_type'=>2 ])->sum('collection_money')+0;
        }

        $info['poundage_number']= $this->modelShopPoundageLog->where(['user_id'=>$uid,'shop_id'=>$info['id']])->sum('total')+$butie;
        $info['max_poundage_number']=get_max_number($info['poundage_number']);
        unset($info->wallet);
        unset($info->member);
        
        return $info;
    }


    /***
     * 额外补贴
     */
    public  function  additional_allowance($data){

        $member=$this->logicApiBase->member;
        $uid=$member['id'];
//dd($uid);
        if(!empty($data['month'])){
            $start=date('Y-'.$data['month'].'-01 00:00:00', strtotime(date("Y-m-d")));
            $end_data=strtotime(date('Y-m-d 23:59:59', strtotime("$start +1 month -1 day")));
            $BeginDate=strtotime($start);
        }else{
            $start=date('Y-m-01 00:00:00', strtotime(date("Y-m-d")));
            $BeginDate=strtotime($start);
            $end_data=strtotime(date('Y-m-d 23:59:59', strtotime("$BeginDate +1 month -1 day")));
        }
        $info['end_time']=$end_data-TIME_NOW;

        $info['collection_money']=OtcOrder::where(['shop_id'=>$data['shop_id'],'create_time'=>['between',[$BeginDate,$end_data]],'uid'=>$uid,'otc_type'=>2 ,'state'=>['in',[2,9,10]]])->sum('total')+0;

        $info['substitute_money']=OtcOrder::where(['shop_id'=>$data['shop_id'],'create_time'=>['between',[$BeginDate,$end_data]],'user_id'=>$uid,'otc_type'=>1 ,'state'=>['in',[2,9,10]]])->sum('total')+0;
        $info['collection_count']=OtcOrder::where(['shop_id'=>$data['shop_id'],'create_time'=>['between',[$BeginDate,$end_data]],'uid'=>$uid,'otc_type'=>2 ,'state'=>['in',[2,9,10]]])->count();
        $info['substitute_count']=OtcOrder::where(['shop_id'=>$data['shop_id'],'create_time'=>['between',[$BeginDate,$end_data]],'user_id'=>$uid,'otc_type'=>1 ,'state'=>['in',[2,9,10]]])->count();
        $shop=OtcShop::get($data['shop_id']);
//        $ids=OtcShop::where(['user_id'=>$uid,'state'=>2,'status'=>1])->column('id');
        $feed_count=OtcFeedback::where(['create_time'=>['between',[$BeginDate,$end_data]],'shop_id'=>$data['shop_id']])->count();
        $info['order_count']=OtcOrder::where(['shop_id'=>$data['shop_id'],'create_time'=>['between',[$BeginDate,$end_data]],'user_id'=>$uid,'otc_type'=>1])->count()+OtcOrder::where(['shop_id'=>$data['shop_id'],'create_time'=>['between',[$BeginDate,$end_data]],'uid'=>$uid,'otc_type'=>2])->count();
        $info['money_money']=OtcInterestLog::where(['shop_id'=>$data['shop_id'],'create_time'=>['between',[$BeginDate,$end_data]],'user_id'=>$uid,'interest_type'=>2 ])->sum('total')+0;
        $info['total_money']=OtcInterestLog::where(['shop_id'=>$data['shop_id'],'user_id'=>$uid,'interest_type'=>2 ])->sum('total')+0;


        $total_money=0;
        $interest_level=InterestAllocation::where(['type'=>2,'status'=>1])->order('id asc')->select();
        foreach ($interest_level as $k=>$v){
            $total_money+=$shop->get_bonus($v['id']);
            //百分比
            $completion_degree=0;
            if($member['is_shop']==1){

                   $collection_money=(int)$v['collection_money'];
                   $collection_money_total=(int)$v['collection_money_total'];
                    if($info['collection_money']>=$collection_money_total || $collection_money==0){
                        $completion_degree+=22.5;
                    }else{

                        if($k==0){
                            $completion_degree+=$info['collection_money']/$v['collection_money_total']*22.5;
                        }else{

                            if($info['collection_money']>=$interest_level[$k - 1]['collection_money_total'] ) {
                                $completion_degree += ($info['collection_money'] - $interest_level[$k - 1]['collection_money_total'] ) / $v['collection_money']  * 22.5;
                            }
                        }

                    }




                if ($info['collection_count'] >= $v['collection_count_total']    || $v['collection_count']==0  ) {
                    $completion_degree += 22.5;
                } else {

                    if ($k == 0) {

                        $completion_degree += $info['collection_count'] / $v['collection_count_total']  * 22.5;
                    } else {
                        if($info['collection_count']>=$interest_level[$k - 1]['collection_count_total']  ){
                            $completion_degree += ($info['collection_count'] - $interest_level[$k - 1]['collection_count_total'] ) / $v['collection_count']  * 22.5;
                        }

                    }

                }




                $collection_money=(int)$v['substitute_money'];
                if ($info['substitute_money'] >= $v['substitute_money_total'] || $collection_money==0) {
                    $completion_degree += 22.5;
                } else {

                    if ($k == 0) {
                        $completion_degree += $info['substitute_money'] / $v['substitute_money_total']  * 22.5;
                    } else {
                        if($info['substitute_money']>=$interest_level[$k - 1]['substitute_money_total'] ) {
                            $completion_degree += ($info['substitute_money'] - $interest_level[$k - 1]['substitute_money_total'] ) / $v['substitute_money']  * 22.5;
                        }
                    }

                }



                if ($info['substitute_count'] >= $v['substitute_count_total'] || $v['substitute_count']==0) {
                    $completion_degree += 22.5;
                } else {

                    if ($k == 0) {
                        $completion_degree += $info['substitute_count'] / $v['substitute_count_total']  * 22.5;
                    } else {
                        if($info['substitute_count']>=$interest_level[$k - 1]['substitute_count_total'] ) {
                            $completion_degree += ($info['substitute_count'] - $interest_level[$k - 1]['substitute_count_total'] ) / $v['substitute_count']  * 22.5;
                        }
                    }

                }


                if($feed_count<=$v['feed_count_total']){
                    $completion_degree+=10;
                }
            }


            $interest_level[$k]['completion_degree']=format_money($completion_degree,2);
            $interest_level[$k]['feedcount']=$feed_count-$v['feed_count_total']>0?$feed_count-$v['feed_count_total']:0;
        }

        $info['bonus']=$total_money;
        $info['list']=$interest_level;
        return $info;


    }

    /***
     * 用户求购出售订单列表
     */

    public function my_trade_list($data){
        switch ($data['order_type']){
            case 1:
                $where=['type'=>$data['type'],'shop_id'=>$data['shop_id'],'state'=>0];

                $list=$this->modelOtcTrading->getList($where,'id,surplus_number,number,is_alipay,is_weixin,shop_id,is_bank,type,user_id,price,surplus_total as total ,wallet_id,state','price asc ,id desc');
                foreach ($list as $k=>$v){
                    $list[$k]['wallet_name']=$v->wallet->data['name'];
                    $list[$k]['trade_count']=$v->shop->total_count;
                    $list[$k]['volume']=$v->shop->completion_rate;
                    unset($v->wallet);
                    unset($v->shop);
                }

                break;
            case 2:
                $where=['shop_id'=>$data['shop_id']];
                if($data['type']==1){

                    $where['otc_type']=1;
                }else{
                    $where['otc_type']=2;

                }
                $where['state']=['in',[1,3]];
                $list=$this->modelOtcOrder->getList($where,'otc_id,id,otc_type,uid,user_id,serial_number,wallet_id,total,create_time,number,total,price,state,pay_type','id desc');
                foreach ($list as $k =>$v){

                    $list[$k]['pay_name']=$v->pay_text;
                    $list[$k]['state_text']=$v->state_text;
                    $wallet_name=$v->wallet->getData('name');
                    $list[$k]['wallet_name']=$wallet_name;
                    $list[$k]['order_name']=$wallet_name;
                    unset($v->wallet);
                }
                return $list;
                break;
            case 3:
                $this->modelOtcFeedback->alias('a');
                $join = [
                    [SYS_DB_PREFIX . 'otc_order o', 'a.order_id = o.id'],
                ];
                $where=['o.otc_type'=>$data['type'],'o.shop_id'=>$data['shop_id']];
                $this->modelOtcFeedback->join = $join;
                $list=$this->modelOtcFeedback->getList($where,'o.otc_id,a.order_id,o.price,o.id,uid,a.user_id,serial_number,o.wallet_id,total,a.create_time,o.number,o.total,a.state,pay_type','id desc');
                foreach ($list as $k =>$v){
                    $list[$k]['pay_name']=$v->otcorder->pay_text;
                    $list[$k]['state_text']=$v->otcorder->state_text;
                    $wallet_name=$v->otcorder->wallet->getData('name');
                    $list[$k]['wallet_name']=$wallet_name;
                    $list[$k]['order_name']=$wallet_name;
                    $list[$k]['total_money']=$v->otcorder->wallet->parities*$v->total;
                    unset($v->otcorder);
                }
                break;
        }
        return $list;

    }

    /***
     * 撤回订单
     */

    public function withdraw_order($data){
        Db::startTrans();
        $uid=$this->logicApiBase->member['id'];
        $info=$this->modelOtcTrading->where(['id'=>$data['id'],'user_id'=>$uid])->lock(true)->find();
        if($info['status']!=1){
            return  ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }
//        $count=$this->modelOtcOrder->where(['otc_id'=>$data['id']])->count();
//        if($count>0){
//            return  ajaxreturn(1,lang('该发布信息下有交易产生无法删除'));
//
//        }


        try{
            //删除订单
            $info->status= -1;
            $info->save();
            //增加商铺余额，扣除商铺冻结
            $shop=$this->modelOtcShop->where(['id'=>$info['shop_id']])->lock(true)->find();
            $shop->cancel_number+=$info['surplus_number'];
            $shop->number_lock-=$info['surplus_number'];
            $shop->save();
            Db::commit();
            return  ajaxreturn(0,lang('撤回成功'));
        }catch (\Exception $e){
            Db::rollback();
            // return  ajaxreturn(1,$e->getMessage());
            return  ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }



    }


    /***
     * 自动撤回订单
     */

    public function auto_withdraw_order($data){
        Db::startTrans();

        $info=$this->modelOtcTrading->where(['id'=>$data['id']])->lock(true)->find();
        if($info['status']!=1){
            return  ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }
//        $count=$this->modelOtcOrder->where(['otc_id'=>$data['id']])->count();
//        if($count>0){
//            return  ajaxreturn(0,lang('撤回成功'));
//
//        }

        try{
            //删除订单
            $info->status= -1;
            $info->save();
            //增加商铺余额，扣除商铺冻结
            $shop=$this->modelOtcShop->where(['id'=>$info['shop_id']])->lock(true)->find();
            $shop->cancel_number+=$info['surplus_number'];
            $shop->number_lock-=$info['surplus_number'];
            $shop->save();
            Db::commit();
            return  ajaxreturn(0,lang('撤回成功'));
        }catch (\Exception $e){
            Db::rollback();
            // return  ajaxreturn(1,$e->getMessage());
            return  ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }



    }

    /**
     * 充值店铺余额
     */

    public function charge_shop($data){
//        if($this->logicApiBase->member['is_shop_recharge']==0){
//            return ajaxreturn(1,lang('您的店铺异常,无法再次转入,请联系客服处理您的账户'));
//        }


        $uid=$this->logicApiBase->member['id'];
//        //        //验证支付密码
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if($data['number']<=0){
            return ajaxreturn(1,lang('数量错误'));
        }


        Db::startTrans();
        $shop=OtcShop::where(['user_id'=>$uid,'wallet_id'=>$data['wallet_id']])->lock(true)->find();
        if(!$shop){
            return ajaxreturn(1,lang('店铺不存在'));
        }
        if($shop['state']!=2){
            return ajaxreturn(1,lang('店铺未通过审核'));
        }
        if($data['number']<=0){
            return ajaxreturn(1,lang('充值金额错误'));
        }
        if($shop['is_transfer_to']==0){
            return ajaxreturn(1,lang('您的店铺异常,无法再次转入,请联系客服处理您的账户'));
        }


        $form=EthAccount::where(['user_id'=>$uid])->lock(true)->find();
        $to_wallet=Wallet::get([$shop['wallet_id']]);
        $do=  $to_wallet['symbol'].'_do';
        if($form[ $do ]<$data['number']){
            return ajaxreturn(1,lang('法币余额不足'));
        }
        try{
            //账户余额扣除
            $form->$do-=$data['number'];
            $form->save();



            EthAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>$shop['wallet_id'],
                'before_blance'=>$form->$do+$data['number'],
                'after_blance'=>$form->$do,
                'remark'=> '从法币转入店铺',
                'is_add'=>2,
                'type'=>7
            ]);




            $shop->number_do+=$data['number'];
            $shop->save();
            ShopAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'shop_id'=>$shop['id'],
                'remark'=> '从法币转入店铺',
                'is_add'=>1,
                'type'=>1
            ]);

            Db::commit();


        }catch( \Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

        return ajaxreturn(0,lang('充值成功'));
    }


    /***
     * 申请店铺
     */
    public function  apply_shop($data){
        $validate_result = $this->validateOtcshop->scene('api_add')->check($data);

        if (!$validate_result) {
            return ajaxreturn(1,lang($this->validateOtcshop->getError()));

        }
        $member=$this->logicApiBase->member;
        $data['user_name']=$member['username'];
        if( !explode(',',$data['pay_type']) ){
            return ajaxreturn(1,lang('参数错误'));
        }
        $data['user_id']=$member['id'];
        $data['state']=1;
        $shop=OtcShop::get(['idcard'=>$data['idcard'],'user_id'=>['neq',$member['id']]]);
        if($shop){
            return ajaxreturn(1,lang('身份证号码已被注册'));
        }
        $shop=OtcShop::get(['shop_name'=>$data['shop_name'],'user_id'=>['neq',$member['id']]]);
        if($shop){
            return ajaxreturn(1,lang('店铺名已被注册'));
        }
        if(strlen($data['idcard'])!=15 && strlen($data['idcard'])!=18 ){
            return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
        }
        if(getConfig('idcard_switch')==1){
            if(!is_idcard($data['idcard'])){
                return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
            }

            if (!checkName($data['true_name'])) {
                return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
            }
            $idcard_info=Idcard::get(['idCard'=>$data['idcard']]);
            if($idcard_info){
                if($idcard_info['name']!=$data['true_name']){
                    return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
                }

            }else{
                $count=cache('idcard'.$member['id'])+0;
                if($count>3){
                    return ajaxreturn(1,lang('身份证姓名错误过多'));
                }
                if(getConfig('idcard_switch')==1){
                    $idcard_getinfo=check_card($data['idcard'],$data['true_name']);
                    if($idcard_getinfo){
                        if($idcard_getinfo['status']=="01"){
                            unset($idcard_getinfo['status']);
                            unset($idcard_getinfo['msg']);
                            unset($idcard_getinfo['prefecture']);

                            $idcard_getinfo['sex']=='男'?$idcard_getinfo['sex']=1:$idcard_getinfo['sex']=2;
                            Idcard::create($idcard_getinfo);
                        }else{

                            cache('idcard'.$member['id'],$count+1,86400);
                            return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
                        }
                    }else{
                        return ajaxreturn(1,lang('身份证验证失败'));
                    }
                }

            }
        }

        if(!empty($data['id'])){
            Db::startTrans();
            try {

                $this->modelOtcShop->setInfo($data);
                user_notice($member['id'],'您的店铺申请成功，请耐心等待客服审核');
                Db::commit();
                return ajaxreturn(0,lang('申请成功'));
            } catch (\Exception $e) {
                Db::rollback();
                //return ajaxreturn(1,$e->getMessage());
                return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
            }
        }else{
            if( !$wallet_ids=explode(',',$data['wallet_id']) ){
                return ajaxreturn(1,lang('参数错误'));
            }
            $datas=[];
            unset($data['access_token']);
            unset($data['user_token']);
            unset($data['lang']);
            $data['create_time']=TIME_NOW;
            foreach ($wallet_ids as $k =>$v){
                $inf=OtcShop::get(['status'=>1,'user_id'=>$member['id'],'wallet_id'=>$v]);
                if($inf){
                   continue;
                }

                $data['wallet_id']=$v;

                $datas[]=$data;

            }
            Db::startTrans();
            try {
                if($datas){
                    OtcShop::insertall($datas);
                    Db::commit();
                }
                return ajaxreturn(0,lang('申请成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return ajaxreturn(1,$e->getMessage());
                return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
            }

        }


    }


    /**
     * 店铺转入法币
     */

    public function shop_to_currency($data){


        $uid=$this->logicApiBase->member['id'];
//        //        //验证支付密码
        if(empty($data['number'])){
            return ajaxreturn(1,lang('请输入数量'));
        }
        if(!is_numeric($data['number']) ){
            return ajaxreturn(1,lang('格式不正确'));
        }
        if($data['number']<=0){
            return ajaxreturn(1,lang('数量错误'));
        }


        Db::startTrans();
        $shop=OtcShop::where(['user_id'=>$uid,'id'=>$data['id']])->lock(true)->find();
        if(!$shop){
            return ajaxreturn(1,lang('店铺不存在'));
        }
        if($shop['is_transfer_out']==0){
            return ajaxreturn(1,lang('您的店铺异常,无法再次转出,请联系客服处理您的账户'));
        }
        if($shop[ 'number_do' ]<$data['number']){
            return ajaxreturn(1,lang('店铺余额不足'));
        }
        try{
            //店铺余额扣除
            $shop->number_do-=$data['number'];
            $shop->save();
            $poundage=0;
            //写入店铺转入记录
            Transfer::create([
                'form_wallet_id'=>$shop['wallet_id'],
                'to_wallet_id'=>$shop['wallet_id'],
                'number'=>$data['number'],
                'money'=>$data['number']*(1-$poundage/100),
                'poundage_number'=>$data['number']*$poundage/100,
                'type'=>23,
                'user_id'=>$uid,
                'shop_id'=>$shop['id']
            ]);
            ShopAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'shop_id'=>$shop['id'],
                'remark'=> '从店铺申请转入法币',
                'is_add'=>2,
                'type'=>1
            ]);
            $mobile=getConfig('check_notice_mobile');
            $content= '您有一笔店铺转回订单需正在审核中等待您处理';
            $data = [
                'mobile' =>$mobile,
                'content' => $content,
                'create_time' => TIME_NOW,
                'sms_type' => 30,
                'type' => 0,
                'area'=>86
            ];
            $sms=UserSms::create($data);

            if(getConfig('sms_is_test')!=1){
                $state=send_sms($mobile,$content ,config('settings'),86);
                if($state){
                    UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                }
            }
            Db::commit();


        }catch( \Exception $e){
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }

        return ajaxreturn(0,lang('恭喜您，您的店铺申请成功，等待管理后台对您提交的信息进行审核，请注意动态信息'));
    }


    /***
     * 我的商铺
     */
    public function myshop(){
        $uid=$this->logicApiBase->member['id'];
        $info=[];
        $shop_ids=$this->modelOtcShop->where(['user_id'=>$uid,'state'=>2])->column('id');

        $info['order_count']=$this->modelOtcShop->where(['user_id'=>$uid])->sum('total_count');


        $info['days_order_count']=$this->modelOtcOrder->where( ['shop_id'=>['in',$shop_ids],'create_time'=>['between',[TIME_NOW-86400*30,TIME_NOW]]])->count();

        $info['success_order_count']=$this->modelOtcShop->where(['user_id'=>$uid,'state'=>['in',[2,9,10]]])->sum('success_count');
        $info['completion_rate']= $info['order_count']==0?0:format_money($info['success_order_count']/$info['order_count']*100,2);
        $info['total_price']= $this->modelOtcTrading->where(['shop_id'=>['in',$shop_ids],'state'=>0])->sum('surplus_total')+0;
        $info['max_total_price']=get_max_number($info['total_price']);
        $info['success_total_price']= $this->modelOtcShop->where(['user_id'=>$uid,'state'=>2])->sum('turnover');
        $info['max_success_total_price']=get_max_number($info['success_total_price']);
        $info['poundage_number']= $this->modelShopPoundageLog->where(['user_id'=>$uid])->sum('total')+OtcInterestLog::where(['user_id'=>$uid])->sum('total')+0;
        $info['max_poundage_number']=get_max_number($info['poundage_number']);
        $info['shop_count']=OtcShop::where(['user_id'=>$uid,'shop_switch'=>1,'state'=>2])->count();
        $shop_list=$this->modelOtcShop->field('id,pay_type,wallet_id,create_time,shop_switch,number_do,shop_name,state')->where(['user_id'=>$uid])->select();
        foreach ($shop_list as $k=>$v){
            $shop_list[$k]['pay_method']=explode(',',$v['pay_type']);
            $shop_list[$k]['wallet_name']=$v->wallet->data['name'];
            $shop_list[$k]['parities']=$v->wallet->data['parities'];
            $shop_list[$k]['image']=$this->logicApiBase->member['avtar'];
            unset($v->wallet);
        }
        $info['shop_list']=$shop_list;
        return $info;

    }


    public function shop_list($data){
        $where=['a.state'=>2,'a.wallet_id'=>$data['wallet_id'],'a.status'=>1];
        $where['a.shop_switch']=1;
        $where['c.start_time_int']=['neq',0];
        $where['c.start_time_int']=['lt',TIME_NOW];
        $where['c.end_time_int']=['neq',0];
        $where['c.end_time_int']=['gt',TIME_NOW];
        $shop_list=$this->modelOtcShop->alias('a')->field('a.id,a.pay_type,a.wallet_id,a.create_time,a.total_count,a.number_do,a.shop_name,a.state,a.user_id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->order('a.turnover desc ,a.success_count desc,a.completion_rate desc')->limit(3)->select();
        foreach ($shop_list as $k=>$v){
            $shop_list[$k]['pay_method']=explode(',',$v['pay_type']);
            $shop_list[$k]['wallet_name']=$v->wallet->data['name'];
            $shop_list[$k]['parities']=$v->wallet->data['parities'];
            $shop_list[$k]['complaint_count']=OtcFeedback::where(['shop_id'=>$v['id']])->count();
            $shop_list[$k]['image']=$v->member['avtar'];
            unset($v->member);
            unset($v->wallet);
        }
        return $shop_list;
    }


    /**
     *店铺开关
     */
    public function  shop_switch($data){
        $uid=$this->logicApiBase->member['id'];
        if($data['shop_switch']==1){
            $shop=OtcShop::get(['user_id'=>$uid]);
            $has_number=($shop->number_lock+$shop->number_do+$shop->cancel_number)*$shop->wallet->parities;
            //判断商家余额够不够，不够自动关闭店铺
            if($has_number<300){
                return 1;
            }
            OtcShop::where(['user_id'=>$uid])->update(['shop_switch'=>1]);
        }else{
            OtcShop::where(['user_id'=>$uid])->update(['shop_switch'=>2]);
        }
        return ajaxreturn(0,lang('修改成功'));
    }



    /***
     * 店铺设置
     */

    public function shop_setting(){
        $uid=$this->logicApiBase->member['id'];
        $arr['switch']=0;
        $count=OtcShop::where(['user_id'=>$uid,'shop_switch'=>1,'state'=>2])->count();
        if($count>0){
            $arr['switch']=1;
            $arr['switch2']=1;
        }
        $ids=OtcShop::where(['user_id'=>$uid,'shop_switch'=>1,'state'=>2])->column('wallet_id');
        $arr['ids']=Wallet::all(['id'=>['in',$ids]]);
        $arr['pattern']=$this->logicApiBase->member['pattern'];
        $arr['single_amount']=$this->logicApiBase->member['single_amount'];
        $arr['is_intellect']=$this->logicApiBase->member['is_intellect'];
        $arr['start_time']=$this->logicApiBase->member['start_time'];
        $arr['end_time']=$this->logicApiBase->member['end_time'];
        return $arr;

    }

    /***
     * 店铺设置
     */

    public function shop_setting_edit($data){
        $uid=$this->logicApiBase->member['id'];
        //关闭开启店铺
        if( !empty($data['ids'])){
            $ids=explode(',',$data['ids']);
            foreach ($ids as $k=>$v){
                $shop=OtcShop::get(['wallet_id'=>$v,'user_id'=>$uid]);
                $has_number=($shop->number_lock+$shop->number_do+$shop->cancel_number)*$shop->wallet->parities;
                //判断商家余额够不够，不够自动关闭店铺
                if($has_number<300){
                    return 1;
                }
            }

            OtcShop::where(['user_id'=>$uid,'wallet_id'=>['in',$ids]])->update(['shop_switch'=>1]);
            OtcShop::where(['user_id'=>$uid,'wallet_id'=>['not in',$ids]])->update(['shop_switch'=>2]);

        }else{
            OtcShop::where(['user_id'=>$uid])->update(['shop_switch'=>2]);
        }
        if(!empty($data['pattern']) ){
            $this->logicApiBase->member->pattern=$data['pattern'];
        }
        if(!empty($data['single_amount']) ){
            $this->logicApiBase->member->single_amount=$data['single_amount'];
        }
        if(isset($data['single_amount']) && $data['single_amount']=='' ){
            $this->logicApiBase->member->single_amount=0;
        }
        if(!empty($data['is_intellect']) ){
            $this->logicApiBase->member->is_intellect=$data['is_intellect'];
        }
        if(isset($data['is_intellect']) && $data['is_intellect']==0 ){
            $this->logicApiBase->member->is_intellect=$data['is_intellect'];
        }
        if(!empty($data['start_time']) && !empty($data['end_time'])){
            $this->logicApiBase->member->start_time=$data['start_time'];
            $this->logicApiBase->member->start_time_int=strtotime(date('Y-m-d').' '.$data['start_time']);
            $this->logicApiBase->member->end_time=$data['end_time'];
            $this->logicApiBase->member->end_time_int=strtotime(date('Y-m-d').' '.$data['end_time']);
        }
        $this->logicApiBase->member->save();
        return ajaxreturn(0,lang('修改成功'));
    }


    /***
     * 代发订单转移
     */

    public function  order_transfer($data){
        $order=OtcOrder::get($data['id']);
        if($order['otc_type']!=1){
            return ajaxreturn(1,lang('该订单不是代发订单'));
        }
        //转移订单
        $time=TIME_NOW;
        $where=['c.is_black'=>0,'a.type'=>1];
        $ids1=Member::where(['path'=>['like',','.$order['user_id'].',']])->column('id');
        $ids2=explode(',',rtrim($order->user['path'], ","));
        $ids=array_merge($ids1,$ids2);

        $where['a.user_id']=['not in',$ids];
        $where['s.is_match']=1;
        $where['a.state']=0;
        $where['a.surplus_total']=$order['total'];
        $where['s.is_transfer']=['lt',getConfig('shop_max_transfer_count')+1];
        $where['s.shop_switch']=1;
        $where['c.start_time_int']=['neq',0];
        $where['c.start_time_int']=['lt',TIME_NOW];
        $where['c.end_time_int']=['neq',0];
        $where['c.end_time_int']=['gt',TIME_NOW];
        $trade=OtcTrading::alias('a')->field("a.*,surplus_total AS new_price,match_count,a.surplus_number , a.price as all_price")->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->lock(true)->order("feed_count desc ,match_count asc ,price asc ,id asc")->find();
        if(!$trade){
            unset( $where['a.user_id']);
            $where['c.is_company']=1;
            $where['a.user_id']=['neq',$order['user_id']];
            $trade=OtcTrading::alias('a')->field("a.*,surplus_total AS new_price,match_count,a.surplus_number , a.price as all_price")->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->order("feed_count desc ,match_count asc ,price asc ,id asc")->find();

        }
        if(!$trade){
            Db::rollback();
            return ajaxreturn(1,lang('暂无订单适合转移'));
        }

        $arrs=[
            'price'=>$order['price'],
            'wallet_id'=>$trade['wallet_id'],
            'pay_expire_time'=>$time+getConfig('otc_last_time')*60,
            'otc_type'=>$order['otc_type'],
            'shop_id'=>$trade['shop_id'],
            'otc_id'=>$trade['id'],
            'user_id'=>$trade['user_id'],
            'uid'=>$order['uid'],
            'total'=>$order['total'],
            'number'=>$order['number'],
            'order_id'=>$order['id'],
            'withdrwal_id'=>$order['withdrwal_id'],
            'state'=>1,
            'channel'=>'CCIE'

        ];

        OtcOrder::create($arrs);
        $order->state=4;
        $order->shop->is_transfer+=1;
        $trade->save();
        Db::name('transfer')->where(['id'=>$order['withdrwal_id']])->update(['state'=>5]);
        return ajaxreturn(0,lang('转移成功'));


    }


    /**
     * 店铺财务流水
     */
    public function shop_account_log($data){
        $member=$this->logicApiBase->member;
        $info=$this->modelOtcShop->where(['user_id'=>$member['id'],'id'=>$data['id']])->find();
        if(!$info){
            return  ajaxreturn(0,lang('您不是商家'));
        }
        $where=['shop_id'=>$info['id']];
        switch ($data['type']){
            case 1:
                //今天

                $where['create_time']=['between',[getTodayStart(),getTodayEnd()]];
                break;
            case 2:
                //昨天
                $where['create_time']=['between',[getTodayStart()-86400,getTodayEnd()-86400]];
                break;
            case 3:
                //  前天
                $where['create_time']=['between',[getTodayStart()-86400*2,getTodayEnd()-86400*2]];

                break;
            case 4:
                //近7天
                $where['create_time']=['between',[getTodayStart()-86400*7,TIME_NOW]];

                break;
            case 5:

                //近15天
                $where['create_time']=['between',[getTodayStart()-86400*15,TIME_NOW]];

                break;
            case 6:
//              //近30天
                $where['create_time']=['between',[getTodayStart()-86400*30,TIME_NOW]];
                break;
        }

        if (!empty($data['start_time'])) {
            if (!empty($data['end_time'])) {
                $where['create_time']=['between',[strtotime($data['start_time'] . ' 00:00:00'),strtotime($data['end_time'] . ' 23:59:59')]];

            } else {
                $where['create_time']=['between',[strtotime($data['start_time'] . ' 00:00:00'),strtotime($data['start_time'] . ' 23:59:59')]];

            }
        }
        !empty($data['state']) && $where['type']=$data['state'];
        $list=$this->modelShopAccountLog->getList($where);
        return $list;


    }






}
